package com.practice.service.admin.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.practice.common.constant.MessageConstant;
import com.practice.common.result.PageResult;
import com.practice.common.result.Result;
import com.practice.mapper.admin.LinkMapper;
import com.practice.pojo.admin.dto.LinkPageDTO;
import com.practice.pojo.admin.entity.Link;
import com.practice.service.admin.LinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-05-15
 */
@Service
public class LinkServiceImpl extends ServiceImpl<LinkMapper, Link> implements LinkService {

    @Autowired
    private LinkMapper linkMapper;

    //链接详情
    @Override
    public Result linkDetail(Integer id) {
        Link link = linkMapper.selectById(id);
        return Result.success(link);
    }

    //链接删除
    @Override
    public Result linkDelete(Integer id) {
        //非空判断
        if (id == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        linkMapper.deleteById(id);
        return Result.success();
    }

    //链接修改
    @Override
    public Result linkUpdate(Link link) {

        linkMapper.updateById(link);

        return Result.success();
    }

    //链接添加
    @Override
    public Result linkAdd(Link link) {
        linkMapper.insert(link);
        return Result.success();
    }



    //链接列表-分页查询
    @Override
    public Result pageList(LinkPageDTO linkPageDTO) {
        //非空判断
        if (linkPageDTO.getPage() == null) {
            //设置当前页默认值
            linkPageDTO.setPage(1);
        }
        if (linkPageDTO.getLimit() == null) {
            //设置总页默认值
            linkPageDTO.setLimit(10);
        }

        //创建IPage分页对象,设置分页参数
        IPage<Link> page = new Page<>(linkPageDTO.getPage(), linkPageDTO.getLimit());

        //执行分页条件查询
        LambdaQueryWrapper<Link> lqw = new LambdaQueryWrapper<Link>();
        if (linkPageDTO.getType() != null) {
            lqw.like(Link::getType, linkPageDTO.getType());
        }

        IPage<Link> page2 = linkMapper.selectPage(page, lqw);

        //page2对象属性值封装到PageResult对象内并返回
        PageResult pageResult = new PageResult();
        pageResult.setCount(page2.getTotal());
        pageResult.setTotalPages(page2.getPages());
        pageResult.setPageSize(page2.getSize());
        pageResult.setCurrentPage(page2.getCurrent());
        pageResult.setData(page2.getRecords());

        return Result.success(pageResult);
    }
}
